package com.ilink.groundservice.service.impl.Tool;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ilink.groundservice.entity.PO.Tool.AiXToolUsageRecord;
import com.ilink.groundservice.entity.VO.AiX.AiXToolUsageRecordResponse;
import com.ilink.groundservice.mapper.Tool.AiXToolUsageRecordMapper;
import com.ilink.groundservice.service.Tool.AiXToolUsageRecordService;
import com.ilink.ilinkcommon.exception.BizIllegalException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class AiXToolUsageRecordServiceImpl implements AiXToolUsageRecordService {

    private final AiXToolUsageRecordMapper usageRecordMapper;

    @Override
    @Transactional
    public Long createUsageRecord(Long toolId, String userId, String inputConfig, String sessionId, String ipAddress) {
        if (toolId == null) {
            throw new BizIllegalException("工具ID不能为空");
        }
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        if (sessionId == null) {
            throw new BizIllegalException("会话ID不能为空");
        }
        
        AiXToolUsageRecord record = new AiXToolUsageRecord();
        record.setUserId(userId);
        record.setToolId(toolId);
        record.setStartTime(LocalDateTime.now());
        record.setStatus("running");
        record.setInputConfig(inputConfig);
        record.setSessionId(sessionId);
        record.setIpAddress(ipAddress);
        record.setCreatedAt(LocalDateTime.now());
        record.setUpdatedAt(LocalDateTime.now());
        
        int result = usageRecordMapper.insert(record);
        if (result <= 0) {
            throw new BizIllegalException("创建工具使用记录失败");
        }
        
        return record.getRecordId();
    }

    @Override
    @Transactional
    public void updateUsageRecord(String sessionId, String status, String outputResult, String errorMessage) {
        if (sessionId == null) {
            throw new BizIllegalException("会话ID不能为空");
        }
        
        AiXToolUsageRecordResponse existingRecord = usageRecordMapper.selectUsageRecordBySessionId(sessionId);
        if (existingRecord == null) {
            throw new BizIllegalException("工具使用记录不存在");
        }
        
        AiXToolUsageRecord record = new AiXToolUsageRecord();
        record.setRecordId(existingRecord.getRecordId());
        record.setStatus(status);
        record.setOutputResult(outputResult);
        record.setErrorMessage(errorMessage);
        record.setUpdatedAt(LocalDateTime.now());
        
        // 如果是结束状态，计算持续时间
        if ("completed".equals(status) || "failed".equals(status) || "stopped".equals(status)) {
            LocalDateTime endTime = LocalDateTime.now();
            record.setEndTime(endTime);
            if (existingRecord.getStartTime() != null) {
                int duration = (int) ChronoUnit.SECONDS.between(existingRecord.getStartTime(), endTime);
                record.setDuration(duration);
            }
        }
        
        int result = usageRecordMapper.updateById(record);
        if (result <= 0) {
            throw new BizIllegalException("更新工具使用记录失败");
        }
    }

    @Override
    @Transactional
    public void finishUsageRecord(String sessionId, String outputResult) {
        updateUsageRecord(sessionId, "completed", outputResult, null);
    }

    @Override
    public IPage<AiXToolUsageRecordResponse> getUserUsageRecords(String userId, Long toolId, Integer page, Integer size) {
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        Page<AiXToolUsageRecordResponse> pageQuery = new Page<>(page, size);
        return usageRecordMapper.selectUsageRecordPage(pageQuery, userId, toolId);
    }

    @Override
    public AiXToolUsageRecordResponse getUsageRecordBySessionId(String sessionId) {
        if (sessionId == null) {
            throw new BizIllegalException("会话ID不能为空");
        }
        
        return usageRecordMapper.selectUsageRecordBySessionId(sessionId);
    }

    @Override
    public Map<String, Object> getUserUsageStatistics(String userId) {
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        return usageRecordMapper.selectUsageStatistics(userId);
    }

    @Override
    public List<AiXToolUsageRecordResponse> getRecentUsageRecords(String userId, Integer limit) {
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        
        return usageRecordMapper.selectRecentUsageRecords(userId, limit);
    }

    @Override
    public List<Map<String, Object>> getToolUsageRanking(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        
        return usageRecordMapper.selectToolUsageRanking(limit);
    }
} 